package com.xmutca.core.websocket;

import com.xmutca.core.websocket.handler.ChildChannelHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class NettyServer {

	private ChildChannelHandler childChannelHandler;

	private EventLoopGroup bossGroup;
	private EventLoopGroup workGroup;

	private int tcpPort;

	private Channel channel;

	public void start() throws InterruptedException {
		ServerBootstrap b = new ServerBootstrap();
		b.group(bossGroup, workGroup);
		b.channel(NioServerSocketChannel.class);

		//设置tcp_delay，降低时延，不等待
		b.option(ChannelOption.TCP_NODELAY, true);
		b.childHandler(childChannelHandler);

		System.out.println("服务端开启等待客户端连接 ... ...");

		channel = b.bind(tcpPort).sync().channel();
		channel.closeFuture().sync();
	}

	public void stop() {
		channel.close();
	}

	public void setTcpPort(int tcpPort) {
		this.tcpPort = tcpPort;
	}

	public void setWorkGroup(EventLoopGroup workGroup) {
		this.workGroup = workGroup;
	}

	public void setBossGroup(EventLoopGroup bossGroup) {
		this.bossGroup = bossGroup;
	}

	public void setChildChannelHandler(ChildChannelHandler childChannelHandler) {
		this.childChannelHandler = childChannelHandler;
	}
}
